(function(fabric, $) {
  var zIndex = 0;

  //辅助方法加载图片
  var loadImg = function(src) {
    return new Promise(function(resolve, reject) {
      //图片
      var img = new Image();
      img.onload = function() {
        resolve({
          src: src,
          tag: img,
          ok: true
        });
      };

      img.onerror = function() {
        resolve({
          src: src,
          tag: img,
          ok: false
        });
      };

      img.setAttribute("crossOrigin", "anonymous");
      img.src = src + "?time=" + new Date().valueOf();
    });
  };

  //加载所有图片
  var loadAllImgs = function(imgs) {
    var loaders = [];
    for (var index = 0; index < imgs.length; index++) {
      (function(src) {
        loaders.push(loadImg(src));
      })(imgs[index]);
    }
    return Promise.all(loaders);
  };

  //根据src获取对应的img
  var getImgTag = function(src, arr) {
    var result = null;
    for (var index = 0; index < arr.length; index++) {
      var element = arr[index];
      if (element.src === src) {
        result = element.tag;
        break;
      }
    }
    return result;
  };
  var createCanvas = function(_canvas) {
    var canvas = new fabric.Canvas(_canvas.el);
    return canvas;
  };
  //画子对象集合
  var drawChildren = function(canvas, current, context) {
    if (Array.isArray(current)) {
      for (var index = 0; index < current.length; index++) {
        draw(canvas, current[index], context);
      }
    } else {
      draw(canvas, current, context);
    }
  };

  //画集合
  var drawSet = function(canvas, current, context) {
    if (!canvas) {
      throw "必须创建一块画布";
    }
    if (current.children) {
      drawChildren(canvas, current.children, context);
    }
  };

  //画图片
  var drawImage = function(canvas, current, context) {
    if (!canvas) {
      throw "必须创建一块画布";
    }
    zIndex++;
    //图片
    var img = current.tag;
    var fabricImage = new fabric.Image(img, {
      left: current.x,
      top: current.y,
      selectable: false,
      selection: false,
      scaleX: current.width / img.width,
      scaleY: current.height / img.height
    });
    //alert(fabricImage);
    canvas.add(fabricImage);
  };

  //画文本
  var drawText = function(canvas, current, context) {
    if (!canvas) {
      throw "必须创建一块画布";
    }
    zIndex++;
    var text = new fabric.Textbox(current.content, {
      selectable: false,
      selection: false,
      left: current.x,
      top: current.y,
      width: current.width,
      //height: current.height,
      //lineHeight: 20,
      fontSize: current.size,
      splitByGrapheme: true
    });
    // 缩放中限制区域
    //进行缩放控制
    // text.on("scaling", e => {
    //   //不允许调整高度
    //   e.target.lockScalingY = true;
    //   this.posHandle(e.target);
    // });
    canvas.add(text);
  };

  //画图
  var draw = function(canvas, current, context) {
    switch (current.type) {
      case "set":
        drawSet(canvas, current, context);
        break;
      case "image":
        drawImage(canvas, current, context);
        break;
      case "text":
        drawText(canvas, current, context);
      default:
        break;
    }
  };

  //显示
  var render = function(canvas, context) {
    //ui存在则绘图
    if (context.ui) {
      draw(canvas, context.ui, context);
    }
  };

  //设计器类
  var Design = function(id, options) {
    //赋值
    this.id = id;
    this.options = options;

    //内部变量
    var _canvas = options.canvas;
    var _ui = options.ui;
    //工具箱目前尚未支持
    //var _tools = options.tools;

    //创建的fabric画布
    this.canvas = createCanvas(_canvas);

    //显示方法
    //上下文
    this.context = {
      ui: _ui
    };

    render(this.canvas, this.context);
  };

  //主动刷新界面
  Design.prototype.refresh = function() {
    //清除已经存在的图像
    clear(this.paper, this.svg);
    //重新渲染
    render(this.paper, this.context);
  };
  //修改界面并重新渲染
  Design.prototype.setUI = function(ui) {
    //设置渲染的上下文ui对象并且重回
    this.context.ui = ui;
    this.refresh();
  };
  //获取ui
  Design.prototype.getUI = function() {
    return this.context.ui;
  };

  //重设画布的宽和高
  Design.prototype.setSize = function(w, h) {
    if (!this.paper) {
      throw "必须创建一块画布";
    }
    this.paper.setSize(w, h);
  };

  Design.prototype.renderAll = function() {
    if (!this.canvas) {
      throw "必须创建一块画布";
    }
    this.canvas.renderAll();
  };
  //设置事件绑定(uiChange)
  Design.prototype.uiChange = function(handler) {
    this.events["uiChange"] = handler;
  };

  //导出设计器类export Desgin
  window.Design = Design;
  window.Design.loadImg = loadImg;
  window.Design.loadAllImgs = loadAllImgs;
  window.Design.getImgTag = getImgTag;
})(fabric, jQuery);
